import { Component, OnInit, Input, OnChanges, SimpleChanges, OnDestroy } from '@angular/core';
import { LimitedFarm } from '../limited-farm';
import { List } from 'linqts';
import { ApplicationService } from '../../../../service/application.service';

@Component({
    selector: 'app-realtime-power-panel',
    templateUrl: './realtime-power-panel.component.html',
    styleUrls: ['./realtime-power-panel.component.css'],

})
export class RealtimePowerPanelComponent implements OnInit, OnChanges, OnDestroy {
    /**
     * x轴数据对象
     *
     * @private
     * @type {string[]}@memberof RealtimePowerPanelComponent
     */
    private xAxisData: string[] = [];
    /**
     * series数据对象
     *
     * @private
     * @type {number[]}@memberof RealtimePowerPanelComponent
     */
    private seriesData: number[] = [];

    /**
     * 风场集合
     *
     * @type {Farm[]}@memberof RealtimePowerPanelComponent
     */
    @Input()
    farms: LimitedFarm[];
    /**
     * 单位
     *
     * @type {string}@memberof RealtimePowerPanelComponent
     */
    @Input()
    unit = '万kWh';
    @Input()
    public ratio;
    /**
     * 发电量合计
     *
     * @type {number}@memberof RealtimePowerPanelComponent
     */
    total = 0;
    /**
     * echarts实例对象
     *
     * @private
     * @type {*}@memberof RealtimePowerPanelComponent
     */
    private echartsIntance: any;
    /**
     *
     *
     * @private
     * @type {*}@memberof RealtimePowerPanelComponent
     */
    public options: any;
    /**
     * 气泡提示框，常用于展现更详细的数据
     *
     * @private
     * @type {*}@memberof RealtimePowerPanelComponent
     */
    private tooltip: any = {
        // 触发类型，默认数据触发，可选为：'item' | 'axis'
        trigger: 'axis',
        // 坐标轴指示器
        axisPointer: {
            // 默认type为line，可选为：'line' | 'cross' | 'shadow' | 'none'
            type: 'none'
        },
        formatter: function (params: any) {// 内容格式器
            return params[0].name + ': ' + params[0].value;
        },
        /* position: function (point: any, params: any, dom: any) {
             var posDis = window.innerWidth - dom.offsetWidth;
             return posDis < point[0] ? [posDis, '10%'] : [point[0], '10%'];
         }*/
    };

    /**
     * 直角坐标系中横轴数组
     *
     * @private
     * @type {*}@memberof RealtimePowerPanelComponent
     */
    private yAxis: any;
    /**
     * x轴配置
     *
     * @private
     * @type {*}@memberof RealtimePowerPanelComponent
     */
    private xAxis: any = {
        type: 'value',
        splitLine: { show: false },
        axisTick: { show: false },
        axisLine: { show: false },
        axisLabel: {
            show: false,

        }
    };
    /**
     * 数值系列的颜色列表
     *
     * @private
     * @type {*}@memberof RealtimePowerPanelComponent
     */
    private color: string[] = ['#6dc6da'];
    /**
     * 驱动图表生成的数据内容数组
     *
     * @private
     * @type {*}@memberof RealtimePowerPanelComponent
     */
    private series: any = [{
        name: 'hill',
        // 图表类型，必要参数 'line'（折线图） | 'bar'（柱状图） | 'scatter'（散点图） | 'k'（K线图） 'pie'（饼图）|
        // 'radar'（雷达图） | 'chord'（和弦图） | 'force'（力导向布局图） | 'map'（地图）*/
        type: 'pictorialBar',
        // 类目间柱形距离
        barCategoryGap: '-130%',
        barMaxWidth: 100,
        symbol: 'path://m2.73243,2.73243l0,10c0,-4.5 5,-4.5 4.5,-5c0.5,-0.5 -4.5,-0.5 -4.5,-5z',
        // 图形样式
        itemStyle: {
            // 图形的默认样式
            normal: {
                opacity: 0.8
            },
            // 强调样式
            emphasis: {
                opacity: 1
            }
        },
        label: {
            normal: {
                show: true,
                position: 'right',
                textStyle: {
                    color: '#fff'
                },
            }
        },
        data: this.seriesData,
        // 二级层叠控制，同一个canvas（相同zlevel）上z越高约靠顶层。默认为2
        z: 10,
    }];
    /**
     *x轴坐标一行显示字数；配置最多显示5个或者以上就一行显示；少于5个两行显示
     *
     * @type {number}
     * @memberof RealtimePowerPanelComponent
     */
    lineSize = 3;
    lengthSize = 0;
    constructor(
        private application: ApplicationService,

    ) {
        if (this.application.currentMenuParams && this.application.currentMenuParams['lineSize']) {
            this.lineSize = Number(this.application.currentMenuParams['lineSize'].paramValue);
            if (this.lineSize >= 5) {
                this.lineSize = 0;

            } else {
                this.lengthSize = this.lineSize;
            }
        } else {
            this.lengthSize = this.lineSize;
        }

        this.yAxis = {
            type: 'category',
            data: this.xAxisData,
            // 坐标轴小标记，默认不显示
            axisTick: { show: false },
            // 坐标轴线，默认显示
            axisLine: { show: false },
            // 坐标轴文本标签
            axisLabel: {
                interval: 0,
                rotate: 0,
                textStyle: {
                    color: '#8fd8cf',
                },
                formatter: (value) => {

                    let str = '';
                    if (this.lineSize) {
                        for (let i = 0; i < value.length; i++) {
                            if (i % this.lineSize == 0 && i) {
                                str += '\n' + value[i];
                            } else {
                                ;
                                str += value[i];
                            }
                        };
                    } else {
                        str = value;
                    }


                    return str;
                },
            }
        };
    }

    changeData(data: any) {
        
        const limitedFarms: List<LimitedFarm> = new List<LimitedFarm>(data);

        this.total = limitedFarms.Sum(o => o.powerDay.value) * this.ratio;
        // console.log(limitedFarms)
        this.xAxisData.splice(0, this.xAxisData.length);
        this.seriesData.splice(0, this.seriesData.length);
        // console.log(this.seriesData,this.ratio)
        limitedFarms.ForEach(farm => {
            const n: number = farm.powerDay.value * this.ratio;
            this.xAxisData.push(farm.farmName);
            this.seriesData.push(parseFloat(n.toFixed(2)));
        });

        this.seriesData = this.seriesData.reverse();
        this.xAxisData = this.xAxisData.reverse();
        
        this.initOptions();
        this.updateEchart();


    }
    ngOnChanges(changes: SimpleChanges): void {
      
        if (changes['farms'] && changes['farms'].currentValue) {
            this.changeData(changes['farms'].currentValue);
        }

    }
    ngOnInit() {

        this.initOptions();
        this.updateEchart();

    }
    ngOnDestroy(): void {

    }
    /**
     * 初始化图表
     *
     * @memberof RealtimePowerPanelComponent
     */
    initOptions() {
        if (this.options == null && this.xAxisData && this.xAxisData.length) {
            if (!this.lineSize) {
                this.xAxisData.forEach(o => {
                    const l = o.length;
                    if (l > this.lengthSize) {
                        this.lengthSize = l;
                    }
                });
            }
            this.options = {
                tooltip: this.tooltip,
                grid: {
                    top: 20,
                    bottom: 20,
                    left: 10 + this.lengthSize * 12,
                    right: 60
                },
                xAxis: this.xAxis,
                yAxis: this.yAxis,
                color: this.color,
                series: this.series
            };
            this.updateEchart();
        }
    }
    updateEchart() {
        if (this.echartsIntance != null) {
            this.echartsIntance.setOption(this.options);
        };
    }

    /**
     * 初始化echarts实例
     *
     *
     * @memberof Echart2Component
     */
    onChartInit(ec: any) {
        this.echartsIntance = ec;
    }

    /**
    * 浏览器窗口大小发生改变时触发
    * canvas无法改变大小，只能重绘
    *
    * @memberof Echart2Component
    */
    onResize(event: any) {
        /* console.log('窗口resize')
         if (this.echartsIntance) {
             this.echartsIntance.resize();
         }*/
    }

}



// WEBPACK FOOTER //
// ./src/app/module/monitor/main/realtime-power-panel/realtime-power-panel.component.ts